import Axios from "axios";
import {baseURL} from "@/config";
import {getToken} from "./util";

class HttpRequest {
	constructor(baseUrl = baseURL) {
		// baseUrl = baseURL，es6写法，相当于baseUrl = baseUrl || baseURL
		this.baseUrl = baseUrl;
		// 队列，把请求的url放到栈里
		this.queue = {};
	}

	// 全局配置
	getInsideConfig() {
		return {
			baseUrl: this.baseUrl,
			headers: {}
		};
	}

	// 拦截器
	interceptors(instances, url) {
		// 请求拦截器
		instances.interceptors.request.use(config => {
			// 全局的组件
			// Object.keys(this.queue).length>0，队列里有请求
			if (!Object.keys(this.queue).length) {
				// Spin.show();
			}
			// 把当前的url放到栈中
			this.queue[url] = true;
			config.headers['Authorization'] = getToken();
			return config;
		}, error => {
			return Promise.reject(error);
		});

		//响应拦截器
		instances.interceptors.response.use(res => {
			// this.destroy(url);
			// 对象中删除属性
			delete this.queue[url];
			// 对返回请求进行筛选
			// const {data, status} = res;
			// return {data, status};
			const {data} = res;
			return {data};
		}, error => {
			delete this.queue[url];
			return Promise.reject(error.response.data);
		})
	}

	request(options) {
		// 创建实例
		const instance = Axios.create();
		// Object.assign() 对象合并，Object.assign({a:1},{b:2}); --> {a: 1, b: 2}
		options = Object.assign(this.getInsideConfig(), options);
		this.interceptors(instance, options.url);
		return instance(options);
	}
}

export default HttpRequest;
